/**
 * vue2.0响应式原理
 */
let oldArrayMethods = Array.prototype;
let arrayMethods = Object.create(oldArrayMethods);

function updateView() {
    console.log("视图更新了");
}
function isObject(obj) {
    return typeof obj !== null && typeof obj === "object";
}

["push", "shift", "pop", "unshift"].forEach((method) => {
    arrayMethods[method] = function (...args) {
        updateView();
        Observe(args[0]);
        oldArrayMethods[method].apply(this, args);
    };
});

function Observe(obj) {
    if (!isObject(obj)) {
        return obj;
    }
    if (Array.isArray(obj)) {
        obj.__proto__ = arrayMethods;
    }
    for (let key in obj) {
        defineReactive(obj, key, obj[key]);
    }
}
function defineReactive(obj, key, value) {
    Observe(value);
    Object.defineProperty(obj, key, {
        get() {
            return value;
        },
        set(newVal) {
            if (newVal !== value) {
                Observe(newVal);
                value = newVal;
                updateView();
            }
        },
    });
}
let obj = { name: "gu", age: { n: 13 }, nums: [2, 3, 4] };
Observe(obj);
obj.nums.push(5);
console.log(obj.nums);
